﻿using AzureFileDepot.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SubscribingService
{
    public partial class SubscribingService : ServiceBase
    {
        Thread mWorker;
        AutoResetEvent mStop = new AutoResetEvent(false);

        public SubscribingService()
        {
            InitializeComponent();
            this.ServiceName = "AzureFileDepot Subscriber";
            this.EventLog.Source = "AzureFileDepot";
            this.EventLog.Log = "Application";

            if (!EventLog.SourceExists(this.EventLog.Source))
                EventLog.CreateEventSource(this.EventLog.Source, "Application");
        }

        protected override void OnStart(string[] args)
        {
            this.EventLog.WriteEntry(string.Format("Starting Service '{0}'", this.ServiceName));

            mWorker = new Thread(DoWork);
            mWorker.Start();

            base.OnStart(args);
        }

        protected override void OnStop()
        {
            this.EventLog.WriteEntry(string.Format("Stopping Service '{0}'", this.ServiceName));

            // Signal worker to stop and wait until it does
            mStop.Set();
            mWorker.Join();
        }

        private void DoWork(object arg)
        {
            ServiceBusTopic topic = new ServiceBusTopic(Properties.Settings.Default.ServiceBusAccessSig, "filepublication");
            
            topic.CreateSubscription(Properties.Settings.Default.SubscriberName);

            // Worker thread loop
            for (; ; )
            {
                // Run this code once every 1 second or stop right away if the service is stopped
                if (mStop.WaitOne(1000)) return;

                // Do work...
                string blobPath = topic.GetMessage();
                if (blobPath != null)
                {
                    Console.WriteLine(string.Format("New File: {0}", blobPath));

                    Uri blobURI = new Uri(blobPath);
                    string fileName = blobURI.Segments[blobURI.Segments.Length - 1];

                    // create new file and lock
                    Stream saveFile = new FileStream(Properties.Settings.Default.SaveLocation + "/" + fileName, FileMode.OpenOrCreate);
                    AzureBlob.downloadFromBlob(new Uri(blobPath), saveFile);
                    saveFile.Close();
                }
            }
        }

    }
}
